import React, { memo, useState, useEffect } from 'react';
import { Input, Switch, Select } from 'antd';
import './styles/index.less';
import cityList from './lib/city';
import prprovince from './lib/province.json';

export interface baseCityProps {
    id: number;
    spell: string;
    name: string;
}

export interface baseSearchSelectOptions extends baseCityProps {
    value: number;
    label: string;
}

const getList = (type: boolean = true) => {
    let baseList: any = [], baseCityList: baseCityProps[], baseCityLeftList: string[];
    if (type) {
        baseList = cityList.cities;
        baseCityList = Object.values(cityList.cities).flat().map(k => ({ ...k, value: k.id, label: k.name }));
        baseCityLeftList = Object.keys(cityList.cities);
    } else {
        baseList = prprovince;
        baseCityList = Object.values(cityList.cities).flat().map(k => ({ ...k, value: k.id, label: k.name }));
        baseCityLeftList = Object.keys(prprovince);
    }
    return { baseList, baseCityList, baseCityLeftList }
}

const ViewCity: React.FC = () => {
    const [ inputValue, setInputValue ] = useState("");
    const [ cityView, setCityView ] = useState(false);
    const [ switchType, setSwitchType ] = useState(true);
    const { baseList, baseCityList, baseCityLeftList } = getList(switchType);
    const handleFocus = () => setCityView(true);
    const onFilterOption = (input: string, option: baseSearchSelectOptions) =>  (option?.label ?? '').includes(input);
    const onChangeSwitch = (checked: any)=> setSwitchType(checked);

    const onChange = (e:any) => {
        const item: any = baseCityList.find(k => k.id === e);
        setInputValue(item.name);
        setCityView(false);
    }
    const handleClickItem = (item: any) => {
        setCityView(false);
        setInputValue(item.value);
    }

    const handleClickBtn = (item: string) => {
        let el = document.getElementById(item);
        if (el) el.scrollIntoView();
    }

    const setPopoverState = (e: any) => {
        const flag1 = e.target.offsetParent !== document.getElementById('city-box');
        const flag2 = e.target !== document.getElementById('search-city-box');
        const flag3 = e.target.offsetParent !== document.getElementById('switch');
        const flag4 = e.target.offsetParent !== document.getElementsByClassName('city-box-list')[0];
        if (flag2 && flag1 && flag3 && flag4) setCityView(false);
    }

    useEffect(() => {
        document.addEventListener('click', setPopoverState);
        return () => {
            document.removeEventListener('click', setPopoverState);
        }
    }, [])

    return (
        <div className='city-box' id='city-box'>
            <Input 
                placeholder='请选择城市'
                value={inputValue}
                onFocus={handleFocus}
            />
            {
                cityView && <div className='city-box-list'>
                    <div className='city-box-list-header'>
                        <Switch
                            id='switch'
                            checkedChildren="按城市" 
                            unCheckedChildren="按省份" 
                            defaultChecked 
                            onChange={onChangeSwitch}
                        />
                        <Select
                            className='city-box-list-header-search'
                            id="search-city-box"
                            showSearch
                            placeholder="请搜索城市"
                            optionFilterProp="children"
                            onChange={onChange}
                            filterOption={(input, option) => onFilterOption(input, option as baseSearchSelectOptions)}
                            options={baseCityList as baseCityProps[]}
                        />
                    </div>
                    <div className='city-box-list-search'>
                        { baseCityLeftList.map((k,i) => <div key={i} onClick={() => handleClickBtn(k)}>{k as string}</div>) }
                    </div>
                    <div className='city-content'>
                        {
                            switchType && baseCityLeftList.map((k,i) => (
                                <div className='city-item' key={i}>
                                    <div className='city-item-left' id={k}>{ k as string }</div>
                                    <div className='city-item-right'>
                                        { baseList[k].map((v: any, m: any) => <span className='item-span' key={m} onClick={() => handleClickItem({ ...baseList[k][m], value: baseList[k][m]['name'] })}>{v.name}</span>) }
                                    </div>
                                </div>
                            ))
                        }
                        {
                            !switchType && baseCityLeftList.map((k,i) => {
                                return baseList[k].map((v: any, m: any) => {
                                    return (
                                        <div className='city-item' key={`${m}_${i}`}>
                                            <div className='city-item-left' id={k}>{ v.name }</div>
                                            <div className='city-item-right'>
                                                { v.data.map((e: any, f: any) => <span className='item-span' key={f}  onClick={() => handleClickItem({ id: v.id, name: v.name, value: e })}>{ e }</span>)}
                                            </div>
                                        </div>
                                    )
                                })
                            })
                        }
                    </div>
                </div>
            }
            
        </div>
    )
}

export default memo(ViewCity);